<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { batchEmployess } from '@/api/employess'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 限制文件的大小
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 批量导入信息
    async loadEmployess(data) {
      try {
        const res = await batchEmployess(data)
        if (res.code !== 10000) return this.$message.error(res.message)
        // 导入表格成功后返回上一页面
        this.$router.back()
      } catch (error) {
        console.log(error)
      }
    },
    // 中文转换英文
    tarnZhkeyToEnkey(data) {
      // 1. 映射对象，根据映射对象找英文的键
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      return data.map(item => {
        // console.log(item);
        const obj = {}
        Object.keys(item).forEach(zhkey => {
          // console.log(zhkey);
          const enkey = mapInfo[zhkey]
          // console.log(enkey);
          // console.log(item[zhkey]);
          // 判断是时间的话就转换成标准格式
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            obj[enkey] = new Date(formatExcelDate(item[zhkey]))
          } else {
            obj[enkey] = item[zhkey]
          }
        })
        // console.log(obj);
        return obj
      })
    },
    // 表格内的数据
    handleSuccess({ results, header }) {
      this.tableData = results // 表格数据
      this.tableHeader = header // 表头
      // console.log(results)
      // console.log(header)
      const data = this.tarnZhkeyToEnkey(results)
      // console.log(data)
      // 调用批量导入信息函数 将作为参数传递过去
      this.loadEmployess(data)
    }
  }
}
</script>
